/*
 * Copyright (C) 2012 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mol.market.fanli.ui;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.mol.market.Constants;
import com.mol.market.R;
import com.mol.market.common.network.ApiAsyncTask;
import com.mol.market.common.network.ApiAsyncTask.ApiRequestListener;
import com.mol.market.common.network.MarketAPI;
import com.mol.market.common.util.TopBar;
import com.mol.market.common.util.Utils;
import com.mol.market.common.widget.AppListAdapter;
import com.mol.market.common.widget.BaseActivity;
import com.mol.market.common.widget.LoadingDrawable;

/**
 * 兑换列表界面.
 * 
 * @author Chaos
 * @date 2012-07-25
 * @since Version 0.9.5
 */
public class ExchangeActivityOther extends BaseActivity implements OnClickListener,
        OnItemClickListener, ApiRequestListener {

    /**传递值下一个Activity用的常量_ID.*/
    public static final String INTENT_EXTRA_ID = "id";
    /**传递值下一个Activity用的常量_Title.*/
    public static final String INTENT_EXTRA_TITLE = "title";
    
    /**联网的state*/
    private static final byte STATUS_INIT = -1;
    private static final byte STATUS_OK = 1;
    private static final byte STATUS_ERROR = 0;
    
    private byte mIsLoaded = STATUS_INIT;
    private ArrayList<HashMap<String, Object>> mData;
    private ListView mRecommendList;
    private AppListAdapter mRecommendAdapter;
    private FrameLayout mLoading;
    private ProgressBar mProgress;
    private TextView mNoData;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_exchange);

        initTopBar();

        initView();

        initData();

    }

  /**
   * xihuanzhongguo
   */
    private void initTopBar(){
        TopBar.createTopBar(mSession, 
                this, 
                new View[] { 
                    findViewById(R.id.top_bar_title),
                    findViewById(R.id.top_bar_tv_money), 
                    findViewById(R.id.top_bar_btn_exchange) },
                new int[] { 
                    View.VISIBLE, 
                    View.VISIBLE, 
                    View.GONE },
                getString(R.string.exchange), 
                getString(R.string.task));
    };
    
    private void initView(){
        mRecommendList = (ListView) findViewById(android.R.id.list);
        mLoading = (FrameLayout) findViewById(R.id.loading);
        mProgress = (ProgressBar) findViewById(R.id.progressbar);
        mProgress.setIndeterminateDrawable(new LoadingDrawable(getApplicationContext()));
        mProgress.setVisibility(View.VISIBLE);
        mNoData = (TextView) findViewById(R.id.no_data);
        mNoData.setOnClickListener(this);
        mRecommendList.setEmptyView(mLoading);
    };
    
    private void initData(){
        MarketAPI.getExchangeType(this, this);
    };
    
    /*
     * 预处理返利任务列表数据
     */
    private void handleContent(ArrayList<HashMap<String, Object>> result) {

        if (Utils.checkEmpty(result)) {
            return;
        }

        mData = result;
        mIsLoaded = STATUS_OK;
        bindAdapter();
    }
    
    /*
     * 绑定适配器
     */
    private void bindAdapter() {

        if (mIsLoaded != STATUS_OK) {
            return;
        }

        // 绑定返利任务列表数据
        mRecommendAdapter = new AppListAdapter(
                getApplicationContext(), 
                mData,
                R.layout.fanli_item_exchange, 
                new String[] { 
                    Constants.KEY_ICON,
                    Constants.KEY_PRODUCT_NAME,},
                new int[] { 
                    R.id.iv_icon, 
                    R.id.tv_name,});
        mRecommendAdapter.setActivity(getParent());
        mRecommendList.setAdapter(mRecommendAdapter);
        mRecommendList.setOnItemClickListener(this);
    }

    @SuppressWarnings("unchecked")
    @Override
    public void onSuccess(int method, Object obj) {
        switch (method) {
        case MarketAPI.ACTION_GET_EXCHANGE_TYPE:
            // 显示数据
            handleContent((ArrayList<HashMap<String, Object>>) obj);
            break;
        default:
            break;
        }        
    }

    @Override
    public void onError(int method, int statusCode) {
        switch (method) {
        case MarketAPI.ACTION_GET_EXCHANGE_TYPE:

            if (statusCode == ApiAsyncTask.BUSINESS_ERROR) {

              ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
              //添加兑换记录
              HashMap<String, Object> item = new HashMap<String, Object>();
              item.put(Constants.KEY_ID, Constants.ID_EXCHANGE_RECORD);
              item.put(Constants.KEY_PRODUCT_NAME, getString(R.string.exchange_h));
              item.put(Constants.KEY_ICON, getResources().getDrawable(R.drawable.exchange_records));
              list.add(item);

              //添加收入明细
              item = new HashMap<String, Object>();
              item.put(Constants.KEY_ID, Constants.ID_EXCHANGE_INCOME);
              item.put(Constants.KEY_PRODUCT_NAME, getString(R.string.exchange_d));
              item.put(Constants.KEY_ICON, getResources().getDrawable(R.drawable.income));
              list.add(item);
              handleContent(list);
            } else {
              mIsLoaded = STATUS_ERROR;
              mNoData.setVisibility(View.VISIBLE);
              mProgress.setVisibility(View.GONE);
            }
            break;
        }
    }
    

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
      Utils.jumpToPage(this, ExchangeSelectActivityOther.class, false,
          new String[] { INTENT_EXTRA_ID, INTENT_EXTRA_TITLE },
          new Serializable[] {
              getCurId(mData, position, Constants.KEY_ID),
              getCurTitle(mData, position, Constants.KEY_PRODUCT_NAME)
          });
    }

    @Override
    public void onClick(View v) {
        // 重试
        mNoData.setVisibility(View.GONE);
        mProgress.setVisibility(View.VISIBLE);

        if (mIsLoaded == STATUS_ERROR) {
            mIsLoaded = STATUS_INIT;
            initData();
        }

    }
    
    /**
     * 得到点击的item的ID
     */

    private Integer getCurId(ArrayList<HashMap<String, Object>> result,
        int pos, String key) {
      return Utils.getValue(result, pos, key);
    }


    private String getCurTitle(ArrayList<HashMap<String, Object>> result,
        int pos, String key) {
      return Utils.getValue(result, pos, key);
    }
}
